package com.bank.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bank.dto.Result;
import com.bank.entity.CardInfo;
import com.bank.entity.TradeInfo;
import com.bank.exception.BankException;
import com.bank.mapper.CardInfoMapper;
import com.bank.mapper.TradeInfoMapper;
import com.bank.service.CardInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 银行卡信息服务实现类
 * 实现银行卡信息相关的业务逻辑处理
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2025-06-19
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CardInfoServiceImpl implements CardInfoService {

    @Autowired
    private CardInfoMapper cardInfoMapper;

    @Autowired
    private TradeInfoMapper tradeInfoMapper;

    /**
     * 默认银行卡号前缀
     */
    @Value("${bank.business.card-prefix:10103576}")
    private String cardPrefix;

    /**
     * 默认密码
     */
    @Value("${bank.business.default-password:888888}")
    private String defaultPassword;

    /**
     * 最小余额
     */
    @Value("${bank.business.min-balance:1.00}")
    private BigDecimal minBalance;

    /**
     * 最小开户金额
     */
    @Value("${bank.business.min-open-money:1.00}")
    private BigDecimal minOpenMoney;

    /**
     * 银行卡号正则表达式
     */
    private static final Pattern CARD_ID_PATTERN = Pattern.compile("^[0-9]{16}$");

    /**
     * 密码正则表达式
     */
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^[0-9]{6}$");

    @Override
    public Result<CardInfo> addCard(CardInfo cardInfo) {
        log.info("开始新增银行卡（开户）：{}", cardInfo);

        try {
            // 开户时，初始余额等于开户金额（在验证之前设置）
            if (cardInfo.getBalance() == null && cardInfo.getOpenMoney() != null) {
                cardInfo.setBalance(cardInfo.getOpenMoney());
            }

            // 验证银行卡信息
            Result<Void> validateResult = validateCardInfo(cardInfo);
            if (!validateResult.isSuccess()) {
                return Result.error(validateResult.getMessage());
            }

            // 检查卡号是否已存在
            int cardCount = cardInfoMapper.countByCardId(cardInfo.getCardId());
            if (cardCount > 0) {
                return Result.error("银行卡号已存在，请检查后重试");
            }

            // 设置默认值
            if (StringUtils.isBlank(cardInfo.getCurId())) {
                cardInfo.setCurId("RMB");
            }
            if (cardInfo.getOpenDate() == null) {
                cardInfo.setOpenDate(LocalDate.now());
            }
            if (StringUtils.isBlank(cardInfo.getPassword())) {
                cardInfo.setPassword(defaultPassword);
            }
            if (cardInfo.getIsReportLoss() == null) {
                cardInfo.setIsReportLoss(false);
            }
            // 余额已在验证前设置，这里无需重复设置

            // 插入银行卡信息
            int result = cardInfoMapper.insert(cardInfo);
            if (result > 0) {
                // 记录开户交易
                TradeInfo tradeInfo = new TradeInfo(
                    cardInfo.getCardId(),
                    TradeInfo.TradeType.DEPOSIT,
                    cardInfo.getOpenMoney(),
                    "开户存款"
                );
                tradeInfoMapper.insert(tradeInfo);

                log.info("银行卡开户成功，卡号：{}", cardInfo.getCardId());
                return Result.success("银行卡开户成功", cardInfo);
            } else {
                return Result.error("银行卡开户失败");
            }
        } catch (Exception e) {
            log.error("新增银行卡异常：", e);
            throw new BankException("银行卡开户失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> deleteCard(String cardId) {
        log.info("开始删除银行卡（销户），卡号：{}", cardId);
        
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            // 检查银行卡是否存在
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            // 检查余额是否为0（销户条件）
            if (cardInfo.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                return Result.error("银行卡余额不为0，无法销户。当前余额：" + cardInfo.getBalance());
            }

            // 删除银行卡
            int result = cardInfoMapper.deleteById(cardId);
            if (result > 0) {
                log.info("银行卡销户成功，卡号：{}", cardId);
                return Result.success("银行卡销户成功");
            } else {
                return Result.error("银行卡销户失败");
            }
        } catch (Exception e) {
            log.error("删除银行卡异常：", e);
            throw new BankException("银行卡销户失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> closeAccountWithdraw(String cardId, String password, String remark) {
        log.info("开始销户取款操作，卡号：{}", cardId);

        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            // 验证密码
            Result<Boolean> validateResult = validatePassword(cardId, password);
            if (!validateResult.getData()) {
                return Result.error("密码错误");
            }

            // 检查银行卡是否存在且未挂失
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (cardInfo.getIsReportLoss()) {
                return Result.error("银行卡已挂失，无法进行销户操作");
            }

            BigDecimal withdrawAmount = cardInfo.getBalance();

            // 如果余额为0，直接销户
            if (withdrawAmount.compareTo(BigDecimal.ZERO) == 0) {
                int deleteResult = cardInfoMapper.deleteById(cardId);
                if (deleteResult > 0) {
                    log.info("余额为0的银行卡销户成功，卡号：{}", cardId);
                    return Result.success("银行卡销户成功", BigDecimal.ZERO);
                } else {
                    return Result.error("银行卡销户失败");
                }
            }

            // 记录销户取款交易
            String finalRemark = StringUtils.isBlank(remark) ? "销户取款" : "销户取款-" + remark;
            TradeInfo tradeInfo = new TradeInfo(cardId, TradeInfo.TradeType.WITHDRAW, withdrawAmount, finalRemark);
            int tradeResult = tradeInfoMapper.insert(tradeInfo);

            if (tradeResult > 0) {
                // 将余额设为0
                int updateResult = cardInfoMapper.updateBalance(cardId, BigDecimal.ZERO);
                if (updateResult > 0) {
                    // 删除银行卡
                    int deleteResult = cardInfoMapper.deleteById(cardId);
                    if (deleteResult > 0) {
                        log.info("销户取款操作成功，卡号：{}，取出金额：{}", cardId, withdrawAmount);
                        return Result.success("销户取款成功，取出金额：" + withdrawAmount + "元", withdrawAmount);
                    } else {
                        return Result.error("销户失败");
                    }
                } else {
                    return Result.error("更新余额失败");
                }
            } else {
                return Result.error("记录交易失败");
            }
        } catch (Exception e) {
            log.error("销户取款操作异常：", e);
            throw new BankException("销户取款失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> batchDeleteCards(List<String> cardIds) {
        log.info("开始批量删除银行卡，卡号列表：{}", cardIds);
        
        try {
            if (cardIds == null || cardIds.isEmpty()) {
                return Result.badRequest("银行卡号列表不能为空");
            }

            // 检查每张银行卡的余额
            for (String cardId : cardIds) {
                CardInfo cardInfo = cardInfoMapper.selectById(cardId);
                if (cardInfo != null && cardInfo.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                    return Result.error("银行卡【" + cardId + "】余额不为0，无法销户");
                }
            }

            // 批量删除银行卡
            int result = cardInfoMapper.batchDeleteByIds(cardIds);
            if (result > 0) {
                log.info("批量删除银行卡成功，删除数量：{}", result);
                return Result.success("批量删除银行卡成功，删除数量：" + result);
            } else {
                return Result.error("批量删除银行卡失败");
            }
        } catch (Exception e) {
            log.error("批量删除银行卡异常：", e);
            throw new BankException("批量删除银行卡失败：" + e.getMessage());
        }
    }

    @Override
    public Result<CardInfo> updateCard(CardInfo cardInfo) {
        log.info("开始修改银行卡信息：{}", cardInfo);
        
        try {
            if (StringUtils.isBlank(cardInfo.getCardId())) {
                return Result.badRequest("银行卡号不能为空");
            }

            // 检查银行卡是否存在
            CardInfo existingCard = cardInfoMapper.selectById(cardInfo.getCardId());
            if (existingCard == null) {
                return Result.notFound("银行卡不存在");
            }

            // 验证银行卡信息
            Result<Void> validateResult = validateCardInfo(cardInfo);
            if (!validateResult.isSuccess()) {
                return Result.error(validateResult.getMessage());
            }

            // 更新银行卡信息
            int result = cardInfoMapper.updateById(cardInfo);
            if (result > 0) {
                log.info("银行卡信息修改成功，卡号：{}", cardInfo.getCardId());
                return Result.success("银行卡信息修改成功", cardInfo);
            } else {
                return Result.error("银行卡信息修改失败");
            }
        } catch (Exception e) {
            log.error("修改银行卡信息异常：", e);
            throw new BankException("修改银行卡信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<CardInfo> getCardById(String cardId) {
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            return Result.success(cardInfo);
        } catch (Exception e) {
            log.error("查询银行卡信息异常：", e);
            throw new BankException("查询银行卡信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<CardInfo> getCardDetailById(String cardId) {
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            CardInfo cardInfo = cardInfoMapper.selectDetailByCardId(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            return Result.success(cardInfo);
        } catch (Exception e) {
            log.error("查询银行卡详细信息异常：", e);
            throw new BankException("查询银行卡详细信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<CardInfo>> getCardsByCustomerId(Integer customerId) {
        try {
            if (customerId == null) {
                return Result.badRequest("客户ID不能为空");
            }

            List<CardInfo> cardInfoList = cardInfoMapper.selectByCustomerId(customerId);
            return Result.success(cardInfoList);
        } catch (Exception e) {
            log.error("根据客户ID查询银行卡异常：", e);
            throw new BankException("查询银行卡失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<CardInfo>> getCardsByCustomerNameLike(String customerName) {
        try {
            if (StringUtils.isBlank(customerName)) {
                return Result.badRequest("客户姓名不能为空");
            }

            List<CardInfo> cardInfoList = cardInfoMapper.selectByCustomerNameLike(customerName);
            return Result.success(cardInfoList);
        } catch (Exception e) {
            log.error("根据客户姓名模糊查询银行卡异常：", e);
            throw new BankException("查询银行卡失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<CardInfo>> getCardsByOpenDateRange(LocalDate startDate, LocalDate endDate) {
        try {
            if (startDate == null || endDate == null) {
                return Result.badRequest("开始日期和结束日期不能为空");
            }

            if (startDate.isAfter(endDate)) {
                return Result.badRequest("开始日期不能晚于结束日期");
            }

            List<CardInfo> cardInfoList = cardInfoMapper.selectByOpenDateRange(startDate, endDate);
            return Result.success(cardInfoList);
        } catch (Exception e) {
            log.error("根据开卡日期范围查询银行卡异常：", e);
            throw new BankException("查询银行卡失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<CardInfo>> getCardsByBalanceRange(BigDecimal minBalance, BigDecimal maxBalance) {
        try {
            if (minBalance == null || maxBalance == null) {
                return Result.badRequest("最小余额和最大余额不能为空");
            }

            if (minBalance.compareTo(maxBalance) > 0) {
                return Result.badRequest("最小余额不能大于最大余额");
            }

            List<CardInfo> cardInfoList = cardInfoMapper.selectByBalanceRange(minBalance, maxBalance);
            return Result.success(cardInfoList);
        } catch (Exception e) {
            log.error("根据余额范围查询银行卡异常：", e);
            throw new BankException("查询银行卡失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<IPage<CardInfo>> getCardsPage(Page<CardInfo> page, String cardId, String customerName, Integer savingId,
                                               Boolean isReportLoss, LocalDate startDate, LocalDate endDate,
                                               BigDecimal minBalance, BigDecimal maxBalance) {
        try {
            if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
                return Result.badRequest("开始日期不能晚于结束日期");
            }

            if (minBalance != null && maxBalance != null && minBalance.compareTo(maxBalance) > 0) {
                return Result.badRequest("最小余额不能大于最大余额");
            }

            IPage<CardInfo> result = cardInfoMapper.selectPageWithConditions(page, cardId, customerName, savingId,
                    isReportLoss, startDate, endDate, minBalance, maxBalance);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询银行卡信息异常：", e);
            throw new BankException("查询银行卡信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<Boolean> validatePassword(String cardId, String password) {
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            int count = cardInfoMapper.validatePassword(cardId, password);
            return Result.success(count > 0);
        } catch (Exception e) {
            log.error("验证银行卡密码异常：", e);
            throw new BankException("验证密码失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> changePassword(String cardId, String oldPassword, String newPassword) {
        log.info("开始修改银行卡密码，卡号：{}", cardId);
        
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(oldPassword)) {
                return Result.badRequest("原密码不能为空");
            }

            if (StringUtils.isBlank(newPassword)) {
                return Result.badRequest("新密码不能为空");
            }

            if (!PASSWORD_PATTERN.matcher(newPassword).matches()) {
                return Result.badRequest("新密码格式不正确，应为6位数字");
            }

            // 验证原密码
            Result<Boolean> validateResult = validatePassword(cardId, oldPassword);
            if (!validateResult.getData()) {
                return Result.error("原密码错误");
            }

            // 检查银行卡是否挂失
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (cardInfo.getIsReportLoss()) {
                return Result.error("银行卡已挂失，无法修改密码");
            }

            // 更新密码
            int result = cardInfoMapper.updatePassword(cardId, newPassword);
            if (result > 0) {
                log.info("银行卡密码修改成功，卡号：{}", cardId);
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            log.error("修改银行卡密码异常：", e);
            throw new BankException("修改密码失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> reportLoss(String cardId, String password) {
        log.info("开始银行卡挂失，卡号：{}", cardId);
        
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            // 验证密码
            Result<Boolean> validateResult = validatePassword(cardId, password);
            if (!validateResult.getData()) {
                return Result.error("密码错误");
            }

            // 检查银行卡状态
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (cardInfo.getIsReportLoss()) {
                return Result.error("银行卡已处于挂失状态");
            }

            // 更新挂失状态
            int result = cardInfoMapper.updateReportLossStatus(cardId, true);
            if (result > 0) {
                log.info("银行卡挂失成功，卡号：{}", cardId);
                return Result.success("银行卡挂失成功");
            } else {
                return Result.error("银行卡挂失失败");
            }
        } catch (Exception e) {
            log.error("银行卡挂失异常：", e);
            throw new BankException("银行卡挂失失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> cancelReportLoss(String cardId, String password) {
        log.info("开始银行卡解挂，卡号：{}", cardId);
        
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            // 验证密码
            Result<Boolean> validateResult = validatePassword(cardId, password);
            if (!validateResult.getData()) {
                return Result.error("密码错误");
            }

            // 检查银行卡状态
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (!cardInfo.getIsReportLoss()) {
                return Result.error("银行卡未处于挂失状态");
            }

            // 更新挂失状态
            int result = cardInfoMapper.updateReportLossStatus(cardId, false);
            if (result > 0) {
                log.info("银行卡解挂成功，卡号：{}", cardId);
                return Result.success("银行卡解挂成功");
            } else {
                return Result.error("银行卡解挂失败");
            }
        } catch (Exception e) {
            log.error("银行卡解挂异常：", e);
            throw new BankException("银行卡解挂失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> deposit(String cardId, BigDecimal amount, String remark) {
        log.info("开始存款操作，卡号：{}，金额：{}", cardId, amount);

        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.badRequest("存款金额必须大于0");
            }

            // 检查银行卡是否存在且未挂失
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (cardInfo.getIsReportLoss()) {
                return Result.error("银行卡已挂失，无法进行存款操作");
            }

            // 更新余额
            BigDecimal newBalance = cardInfo.getBalance().add(amount);

            // 先记录交易（使用用户提供的备注）
            TradeInfo tradeInfo = new TradeInfo(cardId, TradeInfo.TradeType.DEPOSIT, amount, remark);
            int tradeResult = tradeInfoMapper.insert(tradeInfo);

            if (tradeResult > 0) {
                // 再更新余额（触发器会自动记录，但我们需要禁用触发器或修改逻辑）
                int result = cardInfoMapper.updateBalance(cardId, newBalance);
                if (result > 0) {
                    log.info("存款操作成功，卡号：{}，存款金额：{}，新余额：{}", cardId, amount, newBalance);
                    return Result.success("存款成功", newBalance);
                } else {
                    return Result.error("存款失败");
                }
            } else {
                return Result.error("存款失败");
            }
        } catch (Exception e) {
            log.error("存款操作异常：", e);
            throw new BankException("存款失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> withdraw(String cardId, String password, BigDecimal amount, String remark) {
        log.info("开始取款操作，卡号：{}，金额：{}", cardId, amount);

        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.badRequest("取款金额必须大于0");
            }

            // 验证密码
            Result<Boolean> validateResult = validatePassword(cardId, password);
            if (!validateResult.getData()) {
                return Result.error("密码错误");
            }

            // 检查银行卡是否存在且未挂失
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            if (cardInfo.getIsReportLoss()) {
                return Result.error("银行卡已挂失，无法进行取款操作");
            }

            // 检查余额是否充足
            if (cardInfo.getBalance().compareTo(amount) < 0) {
                return Result.error("余额不足，当前余额：¥" + cardInfo.getBalance() + "，取款金额：¥" + amount);
            }

            // 计算取款后的余额
            BigDecimal newBalance = cardInfo.getBalance().subtract(amount);

            // 业务规则：取款后余额必须大于等于1元（保护性规则）
            if (newBalance.compareTo(minBalance) < 0) {
                BigDecimal maxWithdrawAmount = cardInfo.getBalance().subtract(minBalance);
                if (maxWithdrawAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("当前余额：¥" + cardInfo.getBalance() + "，为保证账户安全，余额不足1元时无法取款。如需全部取出，请使用销户取款功能。");
                } else {
                    return Result.error("取款后余额不能少于¥" + minBalance + "。当前余额：¥" + cardInfo.getBalance() + "，最多可取：¥" + maxWithdrawAmount + "。如需全部取出，请使用销户取款功能。");
                }
            }

            // 先记录交易（使用用户提供的备注）
            TradeInfo tradeInfo = new TradeInfo(cardId, TradeInfo.TradeType.WITHDRAW, amount, remark);
            int tradeResult = tradeInfoMapper.insert(tradeInfo);

            if (tradeResult > 0) {
                // 再更新余额
                int result = cardInfoMapper.updateBalance(cardId, newBalance);
                if (result > 0) {
                    log.info("取款操作成功，卡号：{}，取款金额：{}，新余额：{}", cardId, amount, newBalance);
                    return Result.success("取款成功", newBalance);
                } else {
                    return Result.error("取款失败");
                }
            } else {
                return Result.error("取款失败");
            }
        } catch (Exception e) {
            log.error("取款操作异常：", e);
            throw new BankException("取款失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<BigDecimal> getBalance(String cardId, String password) {
        try {
            if (StringUtils.isBlank(cardId)) {
                return Result.badRequest("银行卡号不能为空");
            }

            if (StringUtils.isBlank(password)) {
                return Result.badRequest("密码不能为空");
            }

            // 验证密码
            Result<Boolean> validateResult = validatePassword(cardId, password);
            if (!validateResult.getData()) {
                return Result.error("密码错误");
            }

            // 查询余额
            CardInfo cardInfo = cardInfoMapper.selectById(cardId);
            if (cardInfo == null) {
                return Result.notFound("银行卡不存在");
            }

            return Result.success(cardInfo.getBalance());
        } catch (Exception e) {
            log.error("查询余额异常：", e);
            throw new BankException("查询余额失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> generateNewCardId() {
        try {
            String newCardId = cardInfoMapper.generateNewCardId(cardPrefix);
            if (StringUtils.isBlank(newCardId)) {
                // 如果没有找到，生成第一个卡号
                newCardId = cardPrefix + "00000001";
            }
            return Result.success(newCardId);
        } catch (Exception e) {
            log.error("生成新银行卡号异常：", e);
            throw new BankException("生成银行卡号失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<Object> getCardStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", cardInfoMapper.selectTotalCount());
            statistics.put("reportLossCount", cardInfoMapper.selectReportLossCount());
            statistics.put("totalBalance", cardInfoMapper.selectTotalBalance());

            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取银行卡统计信息异常：", e);
            throw new BankException("获取统计信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Result<String> exportCardsToCSV() {
        try {
            List<CardInfo> cardInfoList = cardInfoMapper.selectList(null);

            StringWriter stringWriter = new StringWriter();
            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(
                "卡号", "客户编号", "存款类型编号", "币种", "开卡日期", "开卡金额",
                "账户余额", "是否挂失", "创建时间", "更新时间"
            );

            try (CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat)) {
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                for (CardInfo cardInfo : cardInfoList) {
                    csvPrinter.printRecord(
                        cardInfo.getCardId(),
                        cardInfo.getCustomerId(),
                        cardInfo.getSavingId(),
                        cardInfo.getCurId(),
                        cardInfo.getOpenDate() != null ? cardInfo.getOpenDate().format(dateFormatter) : "",
                        cardInfo.getOpenMoney(),
                        cardInfo.getBalance(),
                        cardInfo.getReportLossText(),
                        cardInfo.getCreateTime() != null ? cardInfo.getCreateTime().format(dateTimeFormatter) : "",
                        cardInfo.getUpdateTime() != null ? cardInfo.getUpdateTime().format(dateTimeFormatter) : ""
                    );
                }
            }

            log.info("银行卡信息导出成功，导出数量：{}", cardInfoList.size());
            return Result.success("银行卡信息导出成功", stringWriter.toString());
        } catch (IOException e) {
            log.error("导出银行卡信息到CSV异常：", e);
            throw new BankException("导出银行卡信息失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Void> validateCardInfo(CardInfo cardInfo) {
        if (cardInfo == null) {
            return Result.badRequest("银行卡信息不能为空");
        }

        if (StringUtils.isBlank(cardInfo.getCardId())) {
            return Result.badRequest("银行卡号不能为空");
        }

        if (!CARD_ID_PATTERN.matcher(cardInfo.getCardId()).matches()) {
            return Result.badRequest("银行卡号格式不正确，应为16位数字");
        }

        if (cardInfo.getCustomerId() == null) {
            return Result.badRequest("客户编号不能为空");
        }

        if (cardInfo.getSavingId() == null) {
            return Result.badRequest("存款类型编号不能为空");
        }

        if (cardInfo.getOpenMoney() == null || cardInfo.getOpenMoney().compareTo(minOpenMoney) < 0) {
            return Result.badRequest("开卡金额不能少于" + minOpenMoney + "元");
        }

        // 注意：开户时balance字段可能为null，会在后续设置
        if (cardInfo.getBalance() != null && cardInfo.getBalance().compareTo(BigDecimal.ZERO) < 0) {
            return Result.badRequest("账户余额不能为负数");
        }

        if (StringUtils.isNotBlank(cardInfo.getPassword()) && !PASSWORD_PATTERN.matcher(cardInfo.getPassword()).matches()) {
            return Result.badRequest("取款密码格式不正确，应为6位数字");
        }

        return Result.success();
    }
}
